package com.hyjiacan.tools.http

import com.hyjiacan.tools.http.models.Session
import java.util.*

class SessionManager {
    companion object {
        const val COOKIE_NAME = "sid"
        private val sessions = mutableMapOf<String, Session>()

        /**
         * 默认的超时为 10 分钟
         */
        const val EXPIRE_TIME = 10 * 60

        fun make(): Session {
            val sessionId = UUID.randomUUID().toString()
            val session = Session(sessionId)
            sessions[sessionId] = session
            return session
        }

        fun get(sessionId: String): Session? {
            if (!sessions.containsKey(sessionId)) {
                println("No session found for sessionId: $sessionId")
                return null
            }
            val session = sessions[sessionId] ?: return null

            val now = System.currentTimeMillis()
            if (now - EXPIRE_TIME * 1000 >= session.lastActiveTime) {
                println("Session $sessionId expired")
                // 过期
                remove(sessionId)
                return null
            }
            session.lastActiveTime = now
            return session
        }

        fun remove(session: Session) {
            remove(session.sessionId)
        }

        fun remove(sessionId: String) {
            sessions.remove(sessionId)
        }
    }
}